<template>
  <div class="article-list">
    <van-pull-refresh
      :success-text="refreshSuccessText"
      :success-duration="1500"
      v-model="isRefreshLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
      <!-- 文章列表 -->
      <articleItem v-for="(article, index) in list"
          :key="index"
          :article="article"/>
        <!-- <van-cell
          v-for="(art, index) in list"
          :key="index"
          :title="art.title"
        /> -->
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticle } from '@/api/article.js'
import articleItem from '@/components/article_item'

export default {
  name: 'ArticleList',
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  components: {
    articleItem
  },
  mounted () {
    console.log(this.channels)
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      timestamp: null,
      isRefreshLoading: false,
      refreshSuccessText: ''
    }
  },
  methods: {
    async onRefresh () {
      try {
        const { data } = await getArticle({
          channel_id: this.channels.id,
          timestamp: Date.now()
        })
        console.log(data)
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        // this.list.unshift(...results)
        this.list = results
        this.onLoad()
        // 下拉刷新关闭
        this.isRefreshLoading = false
        // this.loading = false

        // 提示成功
        this.refreshSuccessText = `刷新成功，更新了${results.length}条数据`
      } catch (err) {
        this.$toast('下拉刷新失败')
      }
    },
    async onLoad () {
      try {
        // 加载更多数据
        // setTimeout 仅做示例，真实场景中一般为 ajax 请求
        const { data } = await getArticle({
          channel_id: this.channels.id,
          timestamp: Date.now()
        })
        console.log(data)
        // 2. 把数据添加到 list 数组中
        const { results } = data.data
        this.list.push(...results)

        // 3.加载状态结束
        this.loading = false
      } catch (err) {
        this.err = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list{
  height: 80vh;
  overflow-y: auto;
}
</style>
